package cn.kgc.springbootdemo.config;


import cn.hutool.core.util.ObjectUtil;
import cn.kgc.springbootdemo.entity.User;
import cn.kgc.springbootdemo.util.TokenUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * <h3>springbootdemo</h3>
 * <p>创建时间、修改时间自动填充配置</p>
 *
 * @author : NiXiaoLong
 * @date : 2021.1.29
 **/
@Configuration
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private TokenUtil tokenUtil;

    /**
     * 插入时的填充策略
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        //获取用户信息
        User user = tokenUtil.getUser();

        //Date类型转LocalDateTime类型
        Date date = new Date();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), zoneId);

        this.setFieldValByName("createTime",localDateTime,metaObject);

        if (ObjectUtil.isNotNull(user)){
        //用户
        this.strictInsertFill(metaObject,"createUserId",User.class,user.getId());
        this.strictInsertFill(metaObject,"createUserName",User.class,user.getUserName());
        }
    }

    /**
     * 更新时的填充策略
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        //Date类型转LocalDateTime类型
        Date date = new Date();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), zoneId);


        this.setFieldValByName("updateTime",localDateTime,metaObject);
    }
}
